<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>碳排放计算器</title>
    <!-- 引入 Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .history-item {
            cursor: pointer;
            margin-bottom: 5px;
        }
        .history-item:hover {
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h1 class="text-center">碳排放计算器</h1>
        <form id="carbonForm" class="mt-4">
            <div class="mb-3">
                <label for="processEmission" class="form-label">工艺排放 (吨):</label>
                <input type="number" class="form-control" id="processEmission" required>
            </div>
            <div class="mb-3">
                <label for="energyConsumption" class="form-label">能源消耗 (吨):</label>
                <input type="number" class="form-control" id="energyConsumption" required>
            </div>
            <div class="mb-3">
                <label for="resourceConsumption" class="form-label">资源消耗 (吨):</label>
                <input type="number" class="form-control" id="resourceConsumption" required>
            </div>
            <div class="mb-3">
                <label for="processFactor" class="form-label">工艺排放因子:</label>
                <input type="number" class="form-control" id="processFactor" value="0.22" required>
            </div>
            <div class="mb-3">
                <label for="energyFactor" class="form-label">能源消耗因子:</label>
                <input type="number" class="form-control" id="energyFactor" value="0.56" required>
            </div>
            <div class="mb-3">
                <label for="resourceFactor" class="form-label">资源消耗因子:</label>
                <input type="number" class="form-control" id="resourceFactor" value="0.33" required>
            </div>
            <button type="button" class="btn btn-primary w-100" id="calculateBtn">计算碳排放</button>
        </form>
        <div id="result" class="mt-4 text-center fs-5 fw-bold"></div>

        <h2 class="mt-5">历史记录</h2>
        <ul id="historyList" class="list-unstyled"></ul>

        <div class="d-flex gap-2 mt-4">
            <button class="btn btn-danger flex-grow-1" id="clearHistoryBtn">清除历史</button>
            <button class="btn btn-success flex-grow-1" id="saveHistoryBtn">保存历史</button>
        </div>
    </div>

    <!-- 引入 jQuery 和 Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function () {
            let db;

            // 初始化数据库
            function initDatabase() {
                return new Promise((resolve, reject) => {
                    const request = window.indexedDB.open('CarbonCalculatorDB', 1);

                    request.onupgradeneeded = function (event) {
                        db = event.target.result;
                        if (!db.objectStoreNames.contains('carbon_history')) {
                            const objectStore = db.createObjectStore('carbon_history', { keyPath: 'id', autoIncrement: true });
                            objectStore.createIndex('time', 'time', { unique: false });
                        }
                    };

                    request.onsuccess = function (event) {
                        db = event.target.result;
                        resolve();
                    };

                    request.onerror = function (event) {
                        reject('无法打开数据库');
                    };
                });
            }

            // 添加历史记录
            function addHistoryRecord(record) {
                return new Promise((resolve, reject) => {
                    const transaction = db.transaction(['carbon_history'], 'readwrite');
                    const objectStore = transaction.objectStore('carbon_history');
                    const request = objectStore.add(record);

                    request.onsuccess = function () {
                        resolve();
                    };

                    request.onerror = function (event) {
                        reject('无法添加记录');
                    };
                });
            }

            // 获取所有历史记录
            function getAllHistoryRecords() {
                return new Promise((resolve, reject) => {
                    const transaction = db.transaction(['carbon_history'], 'readonly');
                    const objectStore = transaction.objectStore('carbon_history');
                    const request = objectStore.getAll();

                    request.onsuccess = function () {
                        resolve(request.result);
                    };

                    request.onerror = function (event) {
                        reject('无法获取记录');
                    };
                });
            }

            // 清除所有历史记录
            function clearHistoryRecords() {
                return new Promise((resolve, reject) => {
                    const transaction = db.transaction(['carbon_history'], 'readwrite');
                    const objectStore = transaction.objectStore('carbon_history');
                    const request = objectStore.clear();

                    request.onsuccess = function () {
                        resolve();
                    };

                    request.onerror = function (event) {
                        reject('无法清除记录');
                    };
                });
            }

            // 初始化并加载历史记录
            initDatabase().then(() => {
                loadHistory();
            }).catch(error => {
                console.error(error);
            });

            // 加载历史记录
            function loadHistory() {
                getAllHistoryRecords().then(records => {
                    $('#historyList').empty();
                    records.reverse().forEach(record => {
                        const li = $(`<li class="history-item" data-id="${record.id}">${record.time}</li>`);
                        $('#historyList').append(li);
                    });
                }).catch(error => {
                    console.error(error);
                });
            }

            // 计算碳排放
            $('#calculateBtn').click(function () {
                const processEmission = parseFloat($('#processEmission').val());
                const energyConsumption = parseFloat($('#energyConsumption').val());
                const resourceConsumption = parseFloat($('#resourceConsumption').val());
                const processFactor = parseFloat($('#processFactor').val());
                const energyFactor = parseFloat($('#energyFactor').val());
                const resourceFactor = parseFloat($('#resourceFactor').val());

                const totalCarbon = (processEmission * processFactor) +
                    (energyConsumption * energyFactor) +
                    (resourceConsumption * resourceFactor);

                $('#result').text(`总碳排放量: ${totalCarbon.toFixed(2)} 吨`);

                // 保存历史记录
                const timestamp = new Date().toLocaleString();
                const record = {
                    time: timestamp,
                    process_emission: processEmission,
                    energy_consumption: energyConsumption,
                    resource_consumption: resourceConsumption,
                    process_factor: processFactor,
                    energy_factor: energyFactor,
                    resource_factor: resourceFactor,
                    total_carbon: totalCarbon
                };

                addHistoryRecord(record).then(() => {
                    loadHistory();
                }).catch(error => {
                    console.error(error);
                });
            });

            // 点击历史记录显示详情
            $('#historyList').on('click', '.history-item', function () {
                const id = $(this).data('id');
                const transaction = db.transaction(['carbon_history'], 'readonly');
                const objectStore = transaction.objectStore('carbon_history');
                const request = objectStore.get(id);

                request.onsuccess = function () {
                    const record = request.result;
                    alert(`时间: ${record.time}\n输入: ${JSON.stringify({
                        process_emission: record.process_emission,
                        energy_consumption: record.energy_consumption,
                        resource_consumption: record.resource_consumption,
                        process_factor: record.process_factor,
                        energy_factor: record.energy_factor,
                        resource_factor: record.resource_factor
                    })}\n结果: ${record.total_carbon.toFixed(2)} 吨`);
                };

                request.onerror = function (event) {
                    console.error('无法获取记录');
                };
            });

            // 清除历史记录
            $('#clearHistoryBtn').click(function () {
                clearHistoryRecords().then(() => {
                    loadHistory();
                }).catch(error => {
                    console.error(error);
                });
            });

            // 保存历史记录为 CSV 文件
            $('#saveHistoryBtn').click(function () {
                getAllHistoryRecords().then(records => {
                    const headers = ["时间", "工艺排放 (吨)", "能源消耗 (吨)", "资源消耗 (吨)", "工艺排放因子", "能源消耗因子", "资源消耗因子", "总碳排放量 (吨)"];
                    const rows = records.map(record => [
                        record.time,
                        record.process_emission,
                        record.energy_consumption,
                        record.resource_consumption,
                        record.process_factor,
                        record.energy_factor,
                        record.resource_factor,
                        record.total_carbon.toFixed(2)
                    ]);

                    const csvContent = "data:text/csv;charset=utf-8," +
                        headers.join(",") + "\n" +
                        rows.map(row => row.join(",")).join("\n");

                    const encodedUri = encodeURI(csvContent);
                    const link = document.createElement("a");
                    link.setAttribute("href", encodedUri);
                    link.setAttribute("download", "carbon_history.csv");
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }).catch(error => {
                    console.error(error);
                });
            });
        });
    </script>
</body>
</html>